<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Spring常用注解 | 风祈的时光录</title><meta name="keywords" content="Spriong，框架"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一些常用的注解">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring常用注解">
<meta property="og:url" content="https://imlql.cn/post/1a003b7b.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="一些常用的注解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png">
<meta property="article:published_time" content="2021-10-05T16:21:58.000Z">
<meta property="article:modified_time" content="2022-07-24T11:22:15.032Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="Spring">
<meta property="article:tag" content="注解">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://npm.elemecdn.com/lql_static@latest/logo/spring.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/1a003b7b"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring常用注解',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:22:15'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://npm.elemecdn.com/lql_static@latest/logo/spring.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring常用注解</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-10-05T16:21:58.000Z" title="发表于 2021-10-06 00:21:58">2021-10-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:22:15.032Z" title="更新于 2022-07-24 19:22:15">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/">Spring</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Spring/%E7%94%A8%E6%B3%95/">用法</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>26分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>参考了尚硅谷注解版，注解版后面的源码没看，雷神讲的太散了</p>
</blockquote>
<h2 id="Spring注解"><a href="#Spring注解" class="headerlink" title="Spring注解"></a>Spring注解</h2><h3 id="AnnotationConfigApplicationContext"><a href="#AnnotationConfigApplicationContext" class="headerlink" title="AnnotationConfigApplicationContext"></a>AnnotationConfigApplicationContext</h3><h3 id="组件添加"><a href="#组件添加" class="headerlink" title="组件添加"></a>组件添加</h3><h4 id="Configuration-Bean"><a href="#Configuration-Bean" class="headerlink" title="@Configuration+@Bean"></a>@Configuration+@Bean</h4><h5 id="XML文件方式"><a href="#XML文件方式" class="headerlink" title="XML文件方式"></a>XML文件方式</h5><h6 id="Person"><a href="#Person" class="headerlink" title="Person"></a>Person</h6><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123; </span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> String name;</span><br><span class="line">    </span><br><span class="line">   <span class="keyword">private</span> Integer age;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> String nickName;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getNickName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> nickName;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNickName</span><span class="params">(String nickName)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.nickName = nickName;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> name;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.name = name;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> Integer <span class="title">getAge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> age;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAge</span><span class="params">(Integer age)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.age = age;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">(String name, Integer age)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">super</span>();</span><br><span class="line">      <span class="keyword">this</span>.name = name;</span><br><span class="line">      <span class="keyword">this</span>.age = age;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">super</span>();</span><br><span class="line">      <span class="comment">// TODO Auto-generated constructor stub</span></span><br><span class="line">   &#125;</span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;Person [name=&quot;</span> + name + <span class="string">&quot;, age=&quot;</span> + age + <span class="string">&quot;, nickName=&quot;</span> + nickName + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h6 id="beans-xml-配置文件"><a href="#beans-xml-配置文件" class="headerlink" title="beans.xml-配置文件"></a>beans.xml-配置文件</h6><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">xmlns:context</span>=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">xmlns:aop</span>=<span class="string">&quot;http://www.springframework.org/schema/aop&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">xmlns:tx</span>=<span class="string">&quot;http://www.springframework.org/schema/tx&quot;</span></span></span><br><span class="line"><span class="tag">   <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">   <span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">&quot;com.atguigu&quot;</span> <span class="attr">use-default-filters</span>=<span class="string">&quot;false&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">context:component-scan</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;person&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.atguigu.bean.Person&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;age&quot;</span> <span class="attr">value</span>=<span class="string">&quot;18&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;name&quot;</span> <span class="attr">value</span>=<span class="string">&quot;zhangsan&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h6 id="MainTest"><a href="#MainTest" class="headerlink" title="MainTest"></a>MainTest</h6><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainTest</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@SuppressWarnings(&quot;resource&quot;)</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		ApplicationContext applicationContext = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">&quot;beans.xml&quot;</span>);</span><br><span class="line">		Person bean = (Person) applicationContext.getBean(<span class="string">&quot;person&quot;</span>);</span><br><span class="line">		System.out.println(bean);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>输出</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Person [name&#x3D;zhangsan, age&#x3D;18, nickName&#x3D;null]</span><br></pre></td></tr></table></figure>

<h5 id="注解方式"><a href="#注解方式" class="headerlink" title="注解方式"></a>注解方式</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//配置类==配置文件</span></span><br><span class="line"><span class="meta">@Configuration</span>  <span class="comment">//告诉Spring这是一个配置类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//给容器中注册一个Bean;类型为返回值的类型，id默认是用方法名作为id(就是bean的名字)，在这里就是person01</span></span><br><span class="line">   <span class="meta">@Bean</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person01</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Person(<span class="string">&quot;lisi&quot;</span>, <span class="number">20</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>或者以下面的这种方式</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//配置类==配置文件</span></span><br><span class="line"><span class="meta">@Configuration</span>  <span class="comment">//告诉Spring这是一个配置类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//这里bean的name就是person</span></span><br><span class="line">    <span class="meta">@Bean(&quot;person&quot;)</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Person <span class="title">person01</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> Person(<span class="string">&quot;lisi&quot;</span>, <span class="number">20</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="ComponentScans"><a href="#ComponentScans" class="headerlink" title="@ComponentScans"></a>@ComponentScans</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//配置类==配置文件</span></span><br><span class="line"><span class="meta">@Configuration</span>  <span class="comment">//告诉Spring这是一个配置类</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@ComponentScans(</span></span><br><span class="line"><span class="meta">      value = &#123;</span></span><br><span class="line"><span class="meta">            @ComponentScan(value=&quot;com.atguigu&quot;,includeFilters = &#123;</span></span><br><span class="line"><span class="meta">/*                @Filter(type=FilterType.ANNOTATION,classes=&#123;Controller.class&#125;),</span></span><br><span class="line"><span class="meta">                  @Filter(type=FilterType.ASSIGNABLE_TYPE,classes=&#123;BookService.class&#125;),*/</span></span><br><span class="line"><span class="meta">                  @Filter(type=FilterType.CUSTOM,classes=&#123;MyTypeFilter.class&#125;)</span></span><br><span class="line"><span class="meta">            &#125;,useDefaultFilters = false)   </span></span><br><span class="line"><span class="meta">      &#125;</span></span><br><span class="line"><span class="meta">      )</span></span><br><span class="line"><span class="comment">//@ComponentScan  value:指定要扫描的包</span></span><br><span class="line"><span class="comment">//excludeFilters = Filter[] ：指定扫描的时候按照什么规则排除那些组件</span></span><br><span class="line"><span class="comment">//includeFilters = Filter[] ：指定扫描的时候只需要包含哪些组件</span></span><br><span class="line"><span class="comment">//FilterType.ANNOTATION：按照注解</span></span><br><span class="line"><span class="comment">//FilterType.ASSIGNABLE_TYPE：按照给定的类型；</span></span><br><span class="line"><span class="comment">//FilterType.ASPECTJ：使用ASPECTJ表达式</span></span><br><span class="line"><span class="comment">//FilterType.REGEX：使用正则指定</span></span><br><span class="line"><span class="comment">//FilterType.CUSTOM：使用自定义规则</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//给容器中注册一个Bean;类型为返回值的类型，id默认是用方法名作为id</span></span><br><span class="line">   <span class="meta">@Bean(&quot;person&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person01</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Person(<span class="string">&quot;lisi&quot;</span>, <span class="number">20</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="自定义TypeFilter指定包扫描规则"><a href="#自定义TypeFilter指定包扫描规则" class="headerlink" title="自定义TypeFilter指定包扫描规则"></a>自定义TypeFilter指定包扫描规则</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyTypeFilter</span> <span class="keyword">implements</span> <span class="title">TypeFilter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * metadataReader：读取到的当前正在扫描的类的信息</span></span><br><span class="line"><span class="comment">    * metadataReaderFactory:可以获取到其他任何类信息的</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">match</span><span class="params">(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)</span></span></span><br><span class="line"><span class="function">         <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      <span class="comment">//获取当前类注解的信息</span></span><br><span class="line">      AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();</span><br><span class="line">      <span class="comment">//获取当前正在扫描的类的类信息</span></span><br><span class="line">      ClassMetadata classMetadata = metadataReader.getClassMetadata();</span><br><span class="line">      <span class="comment">//获取当前类资源（类的路径）</span></span><br><span class="line">      Resource resource = metadataReader.getResource();</span><br><span class="line">      </span><br><span class="line">      String className = classMetadata.getClassName();</span><br><span class="line">      System.out.println(<span class="string">&quot;---&gt;&quot;</span>+className);</span><br><span class="line">      <span class="keyword">if</span>(className.contains(<span class="string">&quot;er&quot;</span>))&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="Scope"><a href="#Scope" class="headerlink" title="@Scope"></a>@Scope</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig2</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> ConfigurableBeanFactory#SCOPE_PROTOTYPE   任何环境都可以使用</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> ConfigurableBeanFactory#SCOPE_SINGLETON   任何环境都可以使用</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST  request    只能在web容器里用</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> org.springframework.web.context.WebApplicationContext#SCOPE_SESSION	 sesssion   只能在web容器里用</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@Scope</span>:调整作用域</span></span><br><span class="line"><span class="comment">	 * prototype：多实例的：ioc容器启动并不会去调用方法创建对象放在容器中。</span></span><br><span class="line"><span class="comment">	 * 					每次获取的时候才会调用方法创建对象；</span></span><br><span class="line"><span class="comment">	 * singleton：单实例的（默认值）：ioc容器启动会调用方法创建对象放到ioc容器中。</span></span><br><span class="line"><span class="comment">	 * 			以后每次获取就是直接从容器（map.get()）中拿，</span></span><br><span class="line"><span class="comment">	 * request：同一次请求创建一个实例</span></span><br><span class="line"><span class="comment">	 * session：同一个session创建一个实例</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * 默认是单实例的</span></span><br><span class="line"><span class="comment">	 * </span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="meta">@Scope(&quot;prototype&quot;)</span></span><br><span class="line">	<span class="meta">@Lazy</span></span><br><span class="line">	<span class="meta">@Bean(&quot;person&quot;)</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Person <span class="title">person</span><span class="params">()</span></span>&#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;给容器中添加Person....&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> Person(<span class="string">&quot;张三&quot;</span>, <span class="number">25</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="Lazy"><a href="#Lazy" class="headerlink" title="@Lazy"></a>@Lazy</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig2</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * </span></span><br><span class="line"><span class="comment">    * 懒加载：</span></span><br><span class="line"><span class="comment">    *        单实例bean：默认在容器启动的时候创建对象；</span></span><br><span class="line"><span class="comment">    *        懒加载：容器启动不创建对象。第一次使用(获取)Bean创建对象，并初始化；</span></span><br><span class="line"><span class="comment">    * </span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Lazy</span></span><br><span class="line">   <span class="meta">@Bean(&quot;person&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;给容器中添加Person....&quot;</span>);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Person(<span class="string">&quot;张三&quot;</span>, <span class="number">25</span>);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>



<h4 id="Conditional"><a href="#Conditional" class="headerlink" title="@Conditional"></a>@Conditional</h4><h5 id="MainConfig2"><a href="#MainConfig2" class="headerlink" title="MainConfig2"></a>MainConfig2</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//类中组件统一设置。满足当前条件，这个类中配置的所有bean注册才能生效；</span></span><br><span class="line"><span class="meta">@Conditional(&#123;WindowsCondition.class&#125;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig2</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@Conditional</span>(&#123;Condition&#125;) ： 按照一定的条件进行判断，满足条件给容器中注册bean</span></span><br><span class="line"><span class="comment">    * </span></span><br><span class="line"><span class="comment">    * 如果系统是windows，给容器中注册(&quot;bill&quot;)</span></span><br><span class="line"><span class="comment">    * 如果是linux系统，给容器中注册(&quot;linus&quot;)</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Bean(&quot;bill&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person01</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Person(<span class="string">&quot;Bill Gates&quot;</span>,<span class="number">62</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Conditional(LinuxCondition.class)</span></span><br><span class="line">   <span class="meta">@Bean(&quot;linus&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person02</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Person(<span class="string">&quot;linus&quot;</span>, <span class="number">48</span>);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="LinuxCondition"><a href="#LinuxCondition" class="headerlink" title="LinuxCondition"></a>LinuxCondition</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//判断是否linux系统</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinuxCondition</span> <span class="keyword">implements</span> <span class="title">Condition</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * ConditionContext：判断条件能使用的上下文（环境）</span></span><br><span class="line"><span class="comment">    * AnnotatedTypeMetadata：注释信息</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">matches</span><span class="params">(ConditionContext context, AnnotatedTypeMetadata metadata)</span> </span>&#123;</span><br><span class="line">      <span class="comment">// TODO是否linux系统</span></span><br><span class="line">      <span class="comment">//1、能获取到ioc使用的beanfactory</span></span><br><span class="line">      ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();</span><br><span class="line">      <span class="comment">//2、获取类加载器</span></span><br><span class="line">      ClassLoader classLoader = context.getClassLoader();</span><br><span class="line">      <span class="comment">//3、获取当前环境信息</span></span><br><span class="line">      Environment environment = context.getEnvironment();</span><br><span class="line">      <span class="comment">//4、获取到bean定义的注册类</span></span><br><span class="line">      BeanDefinitionRegistry registry = context.getRegistry();</span><br><span class="line">      </span><br><span class="line">      String property = environment.getProperty(<span class="string">&quot;os.name&quot;</span>);</span><br><span class="line">      </span><br><span class="line">      <span class="comment">//可以判断容器中的bean注册情况，也可以给容器中注册bean</span></span><br><span class="line">      <span class="keyword">boolean</span> definition = registry.containsBeanDefinition(<span class="string">&quot;person&quot;</span>);</span><br><span class="line">      <span class="keyword">if</span>(property.contains(<span class="string">&quot;linux&quot;</span>))&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h5 id="WindowsCondition"><a href="#WindowsCondition" class="headerlink" title="WindowsCondition"></a>WindowsCondition</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//判断是否windows系统</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WindowsCondition</span> <span class="keyword">implements</span> <span class="title">Condition</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">matches</span><span class="params">(ConditionContext context, AnnotatedTypeMetadata metadata)</span> </span>&#123;</span><br><span class="line">      Environment environment = context.getEnvironment();</span><br><span class="line">      String property = environment.getProperty(<span class="string">&quot;os.name&quot;</span>);</span><br><span class="line">      <span class="keyword">if</span>(property.contains(<span class="string">&quot;Windows&quot;</span>))&#123;</span><br><span class="line">         <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="Import"><a href="#Import" class="headerlink" title="@Import"></a>@Import</h4><h5 id="MainConfig2-1"><a href="#MainConfig2-1" class="headerlink" title="MainConfig2"></a>MainConfig2</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@Import(&#123;Color.class,Red.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class&#125;)</span></span><br><span class="line"><span class="comment">//@Import导入组件，id默认是组件的全类名</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig2</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 给容器中注册组件；</span></span><br><span class="line"><span class="comment">    * 1）、包扫描+组件标注注解（<span class="doctag">@Controller</span>/<span class="doctag">@Service</span>/<span class="doctag">@Repository</span>/<span class="doctag">@Component</span>）[只能注册自己写的类]</span></span><br><span class="line"><span class="comment">    * 2）、<span class="doctag">@Bean</span>[导入的第三方包里面的组件]</span></span><br><span class="line"><span class="comment">    * 3）、<span class="doctag">@Import</span>[快速给容器中导入一个组件]</span></span><br><span class="line"><span class="comment">    *        1）、<span class="doctag">@Import</span>(要导入到容器中的组件)；容器中就会自动注册这个组件，id默认是全类名</span></span><br><span class="line"><span class="comment">    *        2）、ImportSelector:返回需要导入的组件的全类名数组；</span></span><br><span class="line"><span class="comment">    *        3）、ImportBeanDefinitionRegistrar:手动注册bean到容器中</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Bean</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> ColorFactoryBean <span class="title">colorFactoryBean</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> ColorFactoryBean();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="MyImportSelector"><a href="#MyImportSelector" class="headerlink" title="MyImportSelector"></a>MyImportSelector</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//自定义逻辑返回需要导入的组件</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyImportSelector</span> <span class="keyword">implements</span> <span class="title">ImportSelector</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//返回值，就是到导入到容器中的组件全类名</span></span><br><span class="line">   <span class="comment">//AnnotationMetadata:@Import引入MyImportSelector的类的所有注解信息</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="keyword">public</span> String[] selectImports(AnnotationMetadata importingClassMetadata) &#123;</span><br><span class="line">      <span class="comment">//importingClassMetadata.get</span></span><br><span class="line">      <span class="comment">//方法不要返回null值，不然会报错</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> String[]&#123;<span class="string">&quot;com.atguigu.bean.Blue&quot;</span>,<span class="string">&quot;com.atguigu.bean.Yellow&quot;</span>&#125;;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="MyImportBeanDefinitionRegistrar"><a href="#MyImportBeanDefinitionRegistrar" class="headerlink" title="MyImportBeanDefinitionRegistrar"></a>MyImportBeanDefinitionRegistrar</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyImportBeanDefinitionRegistrar</span> <span class="keyword">implements</span> <span class="title">ImportBeanDefinitionRegistrar</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * AnnotationMetadata：当前类的注解信息</span></span><br><span class="line"><span class="comment">    * BeanDefinitionRegistry:BeanDefinition注册类；</span></span><br><span class="line"><span class="comment">    *        把所有需要添加到容器中的bean；调用</span></span><br><span class="line"><span class="comment">    *        BeanDefinitionRegistry.registerBeanDefinition手工注册进来</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)</span> </span>&#123;</span><br><span class="line">      </span><br><span class="line">      <span class="keyword">boolean</span> definition = registry.containsBeanDefinition(<span class="string">&quot;com.atguigu.bean.Red&quot;</span>);</span><br><span class="line">      <span class="keyword">boolean</span> definition2 = registry.containsBeanDefinition(<span class="string">&quot;com.atguigu.bean.Blue&quot;</span>);</span><br><span class="line">      <span class="keyword">if</span>(definition &amp;&amp; definition2)&#123;</span><br><span class="line">         <span class="comment">//指定Bean定义信息；（Bean的类型，Bean。。。）</span></span><br><span class="line">         RootBeanDefinition beanDefinition = <span class="keyword">new</span> RootBeanDefinition(RainBow.class);</span><br><span class="line">         <span class="comment">//注册一个Bean，指定bean名</span></span><br><span class="line">         registry.registerBeanDefinition(<span class="string">&quot;rainBow&quot;</span>, beanDefinition);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Color</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> Car car;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Car <span class="title">getCar</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> car;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCar</span><span class="params">(Car car)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.car = car;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;Color [car=&quot;</span> + car + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Blue</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Blue</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;blue...constructor&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;blue...init...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">detory</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;blue...detory...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="FactoryBean"><a href="#FactoryBean" class="headerlink" title="FactoryBean"></a>FactoryBean</h4><h5 id="MainConfig2-2"><a href="#MainConfig2-2" class="headerlink" title="MainConfig2"></a>MainConfig2</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfig2</span> </span>&#123;</span><br><span class="line">  </span><br><span class="line">   </span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 给容器中注册组件；</span></span><br><span class="line"><span class="comment">    * 1）、包扫描+组件标注注解（<span class="doctag">@Controller</span>/<span class="doctag">@Service</span>/<span class="doctag">@Repository</span>/<span class="doctag">@Component</span>）[自己写的类]</span></span><br><span class="line"><span class="comment">    * 2）、<span class="doctag">@Bean</span>[导入的第三方包里面的组件]</span></span><br><span class="line"><span class="comment">    * 3）、<span class="doctag">@Import</span>[快速给容器中导入一个组件]</span></span><br><span class="line"><span class="comment">    *        1）、<span class="doctag">@Import</span>(要导入到容器中的组件)；容器中就会自动注册这个组件，id默认是全类名</span></span><br><span class="line"><span class="comment">    *        2）、ImportSelector:返回需要导入的组件的全类名数组；</span></span><br><span class="line"><span class="comment">    *        3）、ImportBeanDefinitionRegistrar:手动注册bean到容器中</span></span><br><span class="line"><span class="comment">    * 4）、使用Spring提供的 FactoryBean（工厂Bean）;</span></span><br><span class="line"><span class="comment">    *        1）、默认获取到的是工厂bean调用getObject创建的对象</span></span><br><span class="line"><span class="comment">    *        2）、要获取工厂Bean本身，我们需要给id前面加一个&amp;</span></span><br><span class="line"><span class="comment">    *           &amp;colorFactoryBean</span></span><br><span class="line"><span class="comment">    *</span></span><br><span class="line"><span class="comment">    * 虽然这里装配的是ColorFactoryBean，但实际上beand的类型是Color</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Bean</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> ColorFactoryBean <span class="title">colorFactoryBean</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> ColorFactoryBean();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="ColorFactoryBean"><a href="#ColorFactoryBean" class="headerlink" title="ColorFactoryBean"></a>ColorFactoryBean</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//创建一个Spring定义的FactoryBean</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ColorFactoryBean</span> <span class="keyword">implements</span> <span class="title">FactoryBean</span>&lt;<span class="title">Color</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//返回一个Color对象，这个对象会添加到容器中</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Color <span class="title">getObject</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      System.out.println(<span class="string">&quot;ColorFactoryBean...getObject...&quot;</span>);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Color();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="keyword">public</span> Class&lt;?&gt; getObjectType() &#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      <span class="keyword">return</span> Color.class;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="comment">//是单例？</span></span><br><span class="line">   <span class="comment">//true：这个bean是单实例，在容器中保存一份</span></span><br><span class="line">   <span class="comment">//false：多实例，每次获取都会创建一个新的bean；</span></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isSingleton</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="IOCTest"><a href="#IOCTest" class="headerlink" title="IOCTest"></a>IOCTest</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IOCTest</span> </span>&#123;</span><br><span class="line">   AnnotationConfigApplicationContext applicationContext = <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfig2.class);</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testImport</span><span class="params">()</span></span>&#123;</span><br><span class="line">      printBeans(applicationContext);</span><br><span class="line">      Blue bean = applicationContext.getBean(Blue.class);</span><br><span class="line">      System.out.println(bean);</span><br><span class="line">      </span><br><span class="line">      <span class="comment">//工厂Bean获取的是调用getObject创建的对象</span></span><br><span class="line">      Object bean2 = applicationContext.getBean(<span class="string">&quot;colorFactoryBean&quot;</span>);   </span><br><span class="line">      System.out.println(<span class="string">&quot;bean的类型：&quot;</span>+bean2.getClass()); <span class="comment">//pos_1   输出：bean的类型：class com.atguigu.bean.Color</span></span><br><span class="line">      </span><br><span class="line">      Object bean4 = applicationContext.getBean(<span class="string">&quot;&amp;colorFactoryBean&quot;</span>);</span><br><span class="line">      System.out.println(bean4.getClass()); <span class="comment">//pos_2  输出：class com.atguigu.bean.ColorFactoryBean</span></span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">printBeans</span><span class="params">(AnnotationConfigApplicationContext applicationContext)</span></span>&#123;</span><br><span class="line">      String[] definitionNames = applicationContext.getBeanDefinitionNames();</span><br><span class="line">      <span class="keyword">for</span> (String name : definitionNames) &#123;</span><br><span class="line">         System.out.println(name);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出:</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//前面无关的输出省略</span></span><br><span class="line"></span><br><span class="line">colorFactoryBean</span><br><span class="line">ColorFactoryBean...getObject...</span><br><span class="line">bean的类型：<span class="class"><span class="keyword">class</span> <span class="title">com</span>.<span class="title">atguigu</span>.<span class="title">bean</span>.<span class="title">Color</span></span></span><br><span class="line"><span class="class"><span class="title">class</span> <span class="title">com</span>.<span class="title">atguigu</span>.<span class="title">bean</span>.<span class="title">ColorFactoryBean</span></span></span><br></pre></td></tr></table></figure>



<h3 id="生命周期"><a href="#生命周期" class="headerlink" title="生命周期"></a>生命周期</h3><h4 id="Bean指定初始化和销毁方法"><a href="#Bean指定初始化和销毁方法" class="headerlink" title="@Bean指定初始化和销毁方法"></a>@Bean指定初始化和销毁方法</h4><h5 id="IOCTest-LifeCycle"><a href="#IOCTest-LifeCycle" class="headerlink" title="IOCTest_LifeCycle"></a>IOCTest_LifeCycle</h5><blockquote>
<p>后面的几个用的都是这个测试类</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IOCTest_LifeCycle</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="comment">//1、创建ioc容器</span></span><br><span class="line">      AnnotationConfigApplicationContext applicationContext = <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);</span><br><span class="line">      System.out.println(<span class="string">&quot;容器创建完成...&quot;</span>);</span><br><span class="line">      </span><br><span class="line">      <span class="comment">//applicationContext.getBean(&quot;car&quot;);</span></span><br><span class="line">      <span class="comment">//关闭容器</span></span><br><span class="line">      applicationContext.close();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="MainConfigOfLifeCycle"><a href="#MainConfigOfLifeCycle" class="headerlink" title="MainConfigOfLifeCycle"></a>MainConfigOfLifeCycle</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.atguigu.config;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.context.ApplicationListener;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.ComponentScan;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Scope;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.atguigu.bean.Car;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * bean的生命周期：</span></span><br><span class="line"><span class="comment"> *        bean创建---初始化----销毁的过程</span></span><br><span class="line"><span class="comment"> * 容器管理bean的生命周期；</span></span><br><span class="line"><span class="comment"> * 我们可以自定义初始化和销毁方法；容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 构造（对象创建）</span></span><br><span class="line"><span class="comment"> *        单实例：在容器启动的时候创建对象</span></span><br><span class="line"><span class="comment"> *        多实例：在每次获取的时候创建对象\</span></span><br><span class="line"><span class="comment"> * 初始化：</span></span><br><span class="line"><span class="comment"> * 		对象创建完成，并赋值好，调用初始化方法。。。</span></span><br><span class="line"><span class="comment"> * BeanPostProcessor.postProcessAfterInitialization</span></span><br><span class="line"><span class="comment"> * 销毁：</span></span><br><span class="line"><span class="comment"> * 		单实例：容器关闭的时候</span></span><br><span class="line"><span class="comment"> * 		多实例：容器不会管理这个bean；容器不会调用销毁方法；</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 1）、指定初始化和销毁方法；</span></span><br><span class="line"><span class="comment"> *        通过<span class="doctag">@Bean</span>指定init-method和destroy-method；</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> lfy</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@ComponentScan(&quot;com.atguigu.bean&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfigOfLifeCycle</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//@Scope(&quot;prototype&quot;)</span></span><br><span class="line">   <span class="meta">@Bean(initMethod=&quot;init&quot;,destroyMethod=&quot;detory&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Car <span class="title">car</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Car();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Car</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Car</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;car constructor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;car ... init...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">detory</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;car ... detory...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="输出"><a href="#输出" class="headerlink" title="输出"></a>输出</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">car constructor...</span><br><span class="line">car ... init...</span><br><span class="line">容器创建完成</span><br><span class="line">car ... detory...</span><br></pre></td></tr></table></figure>



<h4 id="InitializingBean和DisposableBean"><a href="#InitializingBean和DisposableBean" class="headerlink" title="InitializingBean和DisposableBean"></a>InitializingBean和DisposableBean</h4><h5 id="MainConfigOfLifeCycle-1"><a href="#MainConfigOfLifeCycle-1" class="headerlink" title="MainConfigOfLifeCycle"></a>MainConfigOfLifeCycle</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * bean的生命周期：</span></span><br><span class="line"><span class="comment"> *        bean创建---初始化----销毁的过程</span></span><br><span class="line"><span class="comment"> * 容器管理bean的生命周期；</span></span><br><span class="line"><span class="comment"> * 我们可以自定义初始化和销毁方法；容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 构造（对象创建）</span></span><br><span class="line"><span class="comment"> *        单实例：在容器启动的时候创建对象</span></span><br><span class="line"><span class="comment"> *        多实例：在每次获取的时候创建对象\</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * BeanPostProcessor.postProcessBeforeInitialization</span></span><br><span class="line"><span class="comment"> * 初始化：</span></span><br><span class="line"><span class="comment"> *        对象创建完成，并赋值好，调用初始化方法。。。</span></span><br><span class="line"><span class="comment"> * BeanPostProcessor.postProcessAfterInitialization</span></span><br><span class="line"><span class="comment"> * 销毁：</span></span><br><span class="line"><span class="comment"> *        单实例：容器关闭的时候</span></span><br><span class="line"><span class="comment"> *        多实例：容器不会管理这个bean；容器不会调用销毁方法；</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 遍历得到容器中所有的BeanPostProcessor；挨个执行beforeInitialization，</span></span><br><span class="line"><span class="comment"> * 一但返回null，跳出for循环，不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * BeanPostProcessor原理</span></span><br><span class="line"><span class="comment"> * populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值</span></span><br><span class="line"><span class="comment"> * initializeBean</span></span><br><span class="line"><span class="comment"> * &#123;</span></span><br><span class="line"><span class="comment"> * applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);</span></span><br><span class="line"><span class="comment"> * invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化</span></span><br><span class="line"><span class="comment"> * applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);</span></span><br><span class="line"><span class="comment"> *&#125;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 1）、指定初始化和销毁方法；</span></span><br><span class="line"><span class="comment"> *        通过<span class="doctag">@Bean</span>指定init-method和destroy-method；</span></span><br><span class="line"><span class="comment"> * 2）、通过让Bean实现InitializingBean（定义初始化逻辑），</span></span><br><span class="line"><span class="comment"> *              DisposableBean（定义销毁逻辑）;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> lfy</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@ComponentScan(&quot;com.atguigu.bean&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfigOfLifeCycle</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//@Scope(&quot;prototype&quot;)</span></span><br><span class="line">   <span class="meta">@Bean(initMethod=&quot;init&quot;,destroyMethod=&quot;detory&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Car <span class="title">car</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Car();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="Cat"><a href="#Cat" class="headerlink" title="Cat"></a>Cat</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cat</span> <span class="keyword">implements</span> <span class="title">InitializingBean</span>,<span class="title">DisposableBean</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Cat</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;cat constructor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroy</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      System.out.println(<span class="string">&quot;cat...destroy...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      System.out.println(<span class="string">&quot;cat...afterPropertiesSet...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="输出-1"><a href="#输出-1" class="headerlink" title="输出"></a>输出</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">cat constructor...</span><br><span class="line">cat...afterPropertiesSet...</span><br><span class="line">car constructor...</span><br><span class="line">car ... init...</span><br><span class="line">容器创建完成</span><br><span class="line">car ... detory...</span><br><span class="line">cat...destroy...</span><br></pre></td></tr></table></figure>



<h4 id="PostConstruct和-PreDestroy"><a href="#PostConstruct和-PreDestroy" class="headerlink" title="@PostConstruct和@PreDestroy"></a>@PostConstruct和@PreDestroy</h4><h5 id="MainConfigOfLifeCycle-2"><a href="#MainConfigOfLifeCycle-2" class="headerlink" title="MainConfigOfLifeCycle"></a>MainConfigOfLifeCycle</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * bean的生命周期：</span></span><br><span class="line"><span class="comment"> *        bean创建---初始化----销毁的过程</span></span><br><span class="line"><span class="comment"> * 容器管理bean的生命周期；</span></span><br><span class="line"><span class="comment"> * 我们可以自定义初始化和销毁方法；容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 构造（对象创建）</span></span><br><span class="line"><span class="comment"> *        单实例：在容器启动的时候创建对象</span></span><br><span class="line"><span class="comment"> *        多实例：在每次获取的时候创建对象\</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * BeanPostProcessor.postProcessBeforeInitialization</span></span><br><span class="line"><span class="comment"> * 初始化：</span></span><br><span class="line"><span class="comment"> *        对象创建完成，并赋值好，调用初始化方法。。。</span></span><br><span class="line"><span class="comment"> * BeanPostProcessor.postProcessAfterInitialization</span></span><br><span class="line"><span class="comment"> * 销毁：</span></span><br><span class="line"><span class="comment"> *        单实例：容器关闭的时候</span></span><br><span class="line"><span class="comment"> *        多实例：容器不会管理这个bean；容器不会调用销毁方法；</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 遍历得到容器中所有的BeanPostProcessor；挨个执行beforeInitialization，</span></span><br><span class="line"><span class="comment"> * 一但返回null，跳出for循环，不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * BeanPostProcessor原理</span></span><br><span class="line"><span class="comment"> * populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值</span></span><br><span class="line"><span class="comment"> * initializeBean</span></span><br><span class="line"><span class="comment"> * &#123;</span></span><br><span class="line"><span class="comment"> * applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);</span></span><br><span class="line"><span class="comment"> * invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化</span></span><br><span class="line"><span class="comment"> * applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);</span></span><br><span class="line"><span class="comment"> *&#125;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 1）、指定初始化和销毁方法；</span></span><br><span class="line"><span class="comment"> *        通过<span class="doctag">@Bean</span>指定init-method和destroy-method；</span></span><br><span class="line"><span class="comment"> * 2）、通过让Bean实现InitializingBean（定义初始化逻辑），</span></span><br><span class="line"><span class="comment"> *              DisposableBean（定义销毁逻辑）;</span></span><br><span class="line"><span class="comment"> * 3）、可以使用JSR250；</span></span><br><span class="line"><span class="comment"> *        <span class="doctag">@PostConstruct</span>：在bean创建完成并且属性赋值完成；来执行初始化方法</span></span><br><span class="line"><span class="comment"> *        <span class="doctag">@PreDestroy</span>：在容器销毁bean之前通知我们进行清理工作</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> lfy</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@ComponentScan(&quot;com.atguigu.bean&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfigOfLifeCycle</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//@Scope(&quot;prototype&quot;)</span></span><br><span class="line">   <span class="meta">@Bean(initMethod=&quot;init&quot;,destroyMethod=&quot;detory&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Car <span class="title">car</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Car();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="Dog"><a href="#Dog" class="headerlink" title="Dog"></a>Dog</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">implements</span> <span class="title">ApplicationContextAware</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//@Autowired</span></span><br><span class="line">   <span class="keyword">private</span> ApplicationContext applicationContext;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Dog</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;dog constructor...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//对象创建并赋值之后调用</span></span><br><span class="line">   <span class="meta">@PostConstruct</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;Dog....@PostConstruct...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//容器移除对象之前</span></span><br><span class="line">   <span class="meta">@PreDestroy</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">detory</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(<span class="string">&quot;Dog....@PreDestroy...&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      <span class="keyword">this</span>.applicationContext = applicationContext;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="输出-2"><a href="#输出-2" class="headerlink" title="输出"></a>输出</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">cat constructor...</span><br><span class="line">cat...afterPropertiesSet...</span><br><span class="line">dog constructor...</span><br><span class="line">Dog....<span class="meta">@PostConstruct</span>...</span><br><span class="line">car constructor...</span><br><span class="line">car ... init...</span><br><span class="line">容器创建完成</span><br><span class="line">car ... detory...</span><br><span class="line">Dog....<span class="meta">@PreDestroy</span>...</span><br><span class="line">cat...destroy...</span><br></pre></td></tr></table></figure>



<h4 id="BeanPostProcessor"><a href="#BeanPostProcessor" class="headerlink" title="BeanPostProcessor"></a>BeanPostProcessor</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * bean的生命周期：</span></span><br><span class="line"><span class="comment"> *        bean创建---初始化----销毁的过程</span></span><br><span class="line"><span class="comment"> * 容器管理bean的生命周期；</span></span><br><span class="line"><span class="comment"> * 我们可以自定义初始化和销毁方法；容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 构造（对象创建）</span></span><br><span class="line"><span class="comment"> *        单实例：在容器启动的时候创建对象</span></span><br><span class="line"><span class="comment"> *        多实例：在每次获取的时候创建对象\</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * BeanPostProcessor.postProcessBeforeInitialization</span></span><br><span class="line"><span class="comment"> * 初始化：</span></span><br><span class="line"><span class="comment"> *        对象创建完成，并赋值好，调用初始化方法。。。</span></span><br><span class="line"><span class="comment"> * BeanPostProcessor.postProcessAfterInitialization</span></span><br><span class="line"><span class="comment"> * 销毁：</span></span><br><span class="line"><span class="comment"> *        单实例：容器关闭的时候</span></span><br><span class="line"><span class="comment"> *        多实例：容器不会管理这个bean；容器不会调用销毁方法；</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 遍历得到容器中所有的BeanPostProcessor；挨个执行beforeInitialization，</span></span><br><span class="line"><span class="comment"> * 一但返回null，跳出for循环，不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * BeanPostProcessor原理</span></span><br><span class="line"><span class="comment"> * populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值</span></span><br><span class="line"><span class="comment"> * initializeBean</span></span><br><span class="line"><span class="comment"> * &#123;</span></span><br><span class="line"><span class="comment"> * applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);</span></span><br><span class="line"><span class="comment"> * invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化</span></span><br><span class="line"><span class="comment"> * applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);</span></span><br><span class="line"><span class="comment"> *&#125;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 1）、指定初始化和销毁方法；</span></span><br><span class="line"><span class="comment"> *        通过<span class="doctag">@Bean</span>指定init-method和destroy-method；</span></span><br><span class="line"><span class="comment"> * 2）、通过让Bean实现InitializingBean（定义初始化逻辑），</span></span><br><span class="line"><span class="comment"> *              DisposableBean（定义销毁逻辑）;</span></span><br><span class="line"><span class="comment"> * 3）、可以使用JSR250；</span></span><br><span class="line"><span class="comment"> *        <span class="doctag">@PostConstruct</span>：在bean创建完成并且属性赋值完成；来执行初始化方法</span></span><br><span class="line"><span class="comment"> *        <span class="doctag">@PreDestroy</span>：在容器销毁bean之前通知我们进行清理工作</span></span><br><span class="line"><span class="comment"> * 4）、BeanPostProcessor【interface】：bean的后置处理器；</span></span><br><span class="line"><span class="comment"> *        在bean初始化前后进行一些处理工作；</span></span><br><span class="line"><span class="comment"> *        postProcessBeforeInitialization:在初始化之前工作</span></span><br><span class="line"><span class="comment"> *        postProcessAfterInitialization:在初始化之后工作</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * Spring底层对 BeanPostProcessor 的使用；</span></span><br><span class="line"><span class="comment"> *        bean赋值，注入其他组件，<span class="doctag">@Autowired</span>，生命周期注解功能，<span class="doctag">@Async</span>,xxx BeanPostProcessor;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> lfy</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@ComponentScan(&quot;com.atguigu.bean&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfigOfLifeCycle</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//@Scope(&quot;prototype&quot;)</span></span><br><span class="line">   <span class="meta">@Bean(initMethod=&quot;init&quot;,destroyMethod=&quot;detory&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Car <span class="title">car</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Car();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="MyBeanPostProcessor"><a href="#MyBeanPostProcessor" class="headerlink" title="MyBeanPostProcessor"></a>MyBeanPostProcessor</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 后置处理器：初始化前后进行处理工作</span></span><br><span class="line"><span class="comment"> * 将后置处理器加入到容器中</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> lfy</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyBeanPostProcessor</span> <span class="keyword">implements</span> <span class="title">BeanPostProcessor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessBeforeInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      System.out.println(<span class="string">&quot;postProcessBeforeInitialization...&quot;</span>+beanName+<span class="string">&quot;=&gt;&quot;</span>+bean);</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Object <span class="title">postProcessAfterInitialization</span><span class="params">(Object bean, String beanName)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      System.out.println(<span class="string">&quot;postProcessAfterInitialization...&quot;</span>+beanName+<span class="string">&quot;=&gt;&quot;</span>+bean);</span><br><span class="line">      <span class="keyword">return</span> bean;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出</p>
<blockquote>
<p>自己写的组件输出内容</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">car constructor...</span><br><span class="line">postProcessBeforeInitialization...car=&gt;com.atguigu.bean.Car@5ef60048</span><br><span class="line">car ... init...</span><br><span class="line">postProcessAfterInitialization...car=&gt;com.atguigu.bean.Car@5ef60048</span><br><span class="line">cat constructor...</span><br><span class="line">postProcessBeforeInitialization...cat=&gt;com.atguigu.bean.Cat@780cb77</span><br><span class="line">cat...afterPropertiesSet...</span><br><span class="line">postProcessAfterInitialization...cat=&gt;com.atguigu.bean.Cat@780cb77</span><br><span class="line">dog constructor...</span><br><span class="line">postProcessBeforeInitialization...dog=&gt;com.atguigu.bean.Dog@4034c28c</span><br><span class="line">Dog....<span class="meta">@PostConstruct</span>...</span><br><span class="line">postProcessAfterInitialization...dog=&gt;com.atguigu.bean.Dog@4034c28c</span><br><span class="line">容器创建完成...</span><br><span class="line">Dog....<span class="meta">@PreDestroy</span>...</span><br><span class="line">cat...destroy...</span><br><span class="line">car ... detory...</span><br></pre></td></tr></table></figure>



<blockquote>
<ol>
<li>BeanPostProcessor在Spring源码里大量被使用到，仅凭这里雷丰阳老师讲的一点点原理，是无法体会的，建议自己去看看Spring源码。所以这里的原理部分我也就直接省略了，在本视频中讲的太浅了。</li>
</ol>
</blockquote>
<h3 id="属性赋值"><a href="#属性赋值" class="headerlink" title="属性赋值"></a>属性赋值</h3><h4 id="Value和-PropertySource"><a href="#Value和-PropertySource" class="headerlink" title="@Value和@PropertySource"></a>@Value和@PropertySource</h4><h5 id="Person-1"><a href="#Person-1" class="headerlink" title="Person"></a>Person</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//使用@Value赋值；</span></span><br><span class="line">   <span class="comment">//1、基本数值</span></span><br><span class="line">   <span class="comment">//2、可以写SpEL； #&#123;&#125;</span></span><br><span class="line">   <span class="comment">//3、可以写$&#123;&#125;；取出配置文件【properties】中的值（在运行环境变量里面的值）</span></span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Value(&quot;张三&quot;)</span></span><br><span class="line">   <span class="keyword">private</span> String name;</span><br><span class="line">   <span class="meta">@Value(&quot;#&#123;20-2&#125;&quot;)</span></span><br><span class="line">   <span class="keyword">private</span> Integer age;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Value(&quot;$&#123;person.nickName&#125;&quot;)</span></span><br><span class="line">   <span class="keyword">private</span> String nickName;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getNickName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> nickName;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNickName</span><span class="params">(String nickName)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.nickName = nickName;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> name;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.name = name;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> Integer <span class="title">getAge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> age;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAge</span><span class="params">(Integer age)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.age = age;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">(String name, Integer age)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">super</span>();</span><br><span class="line">      <span class="keyword">this</span>.name = name;</span><br><span class="line">      <span class="keyword">this</span>.age = age;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">super</span>();</span><br><span class="line">      <span class="comment">// TODO Auto-generated constructor stub</span></span><br><span class="line">   &#125;</span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;Person [name=&quot;</span> + name + <span class="string">&quot;, age=&quot;</span> + age + <span class="string">&quot;, nickName=&quot;</span> + nickName + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="person-properties"><a href="#person-properties" class="headerlink" title="person.properties"></a>person.properties</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">person.nickName=\u5C0F\u674E\u56DB</span><br></pre></td></tr></table></figure>



<h5 id="MainConfigOfPropertyValues"><a href="#MainConfigOfPropertyValues" class="headerlink" title="MainConfigOfPropertyValues"></a>MainConfigOfPropertyValues</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用$&#123;&#125;取出配置文件的值</span></span><br><span class="line"><span class="meta">@PropertySource(value=&#123;&quot;classpath:/person.properties&quot;&#125;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfigOfPropertyValues</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Bean</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Person <span class="title">person</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Person();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="IOCTest-PropertyValue"><a href="#IOCTest-PropertyValue" class="headerlink" title="IOCTest_PropertyValue"></a>IOCTest_PropertyValue</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IOCTest_PropertyValue</span> </span>&#123;</span><br><span class="line">   AnnotationConfigApplicationContext applicationContext = <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);</span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span></span>&#123;</span><br><span class="line">      printBeans(applicationContext);</span><br><span class="line">      System.out.println(<span class="string">&quot;=============&quot;</span>);</span><br><span class="line">      </span><br><span class="line">      Person person = (Person) applicationContext.getBean(<span class="string">&quot;person&quot;</span>);</span><br><span class="line">      System.out.println(person);</span><br><span class="line">      </span><br><span class="line">      </span><br><span class="line">      ConfigurableEnvironment environment = applicationContext.getEnvironment();</span><br><span class="line">      String property = environment.getProperty(<span class="string">&quot;person.nickName&quot;</span>);</span><br><span class="line">      System.out.println(property);</span><br><span class="line">      applicationContext.close();</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">printBeans</span><span class="params">(AnnotationConfigApplicationContext applicationContext)</span></span>&#123;</span><br><span class="line">      String[] definitionNames = applicationContext.getBeanDefinitionNames();</span><br><span class="line">      <span class="keyword">for</span> (String name : definitionNames) &#123;</span><br><span class="line">         System.out.println(name);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="输出-3"><a href="#输出-3" class="headerlink" title="输出"></a>输出</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line">mainConfigOfPropertyValues</span><br><span class="line">person</span><br><span class="line">=============</span><br><span class="line">Person [name=张三, age=<span class="number">18</span>, nickName=小李四]</span><br><span class="line">小李四</span><br></pre></td></tr></table></figure>



<h3 id="自动装配"><a href="#自动装配" class="headerlink" title="自动装配"></a>自动装配</h3><h4 id="Autowired-Qualifier-Primary-Resource-Inject"><a href="#Autowired-Qualifier-Primary-Resource-Inject" class="headerlink" title="@Autowired-@Qualifier-@Primary-@Resource-@Inject"></a>@Autowired-@Qualifier-@Primary-@Resource-@Inject</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BookController</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Autowired</span></span><br><span class="line">   <span class="keyword">private</span> BookService bookService;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BookService</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">//@Qualifier(&quot;bookDao&quot;)</span></span><br><span class="line">   <span class="comment">//@Autowired(required=false)</span></span><br><span class="line">   <span class="comment">//@Resource(name=&quot;bookDao2&quot;)</span></span><br><span class="line">   <span class="meta">@Inject</span></span><br><span class="line">   <span class="keyword">private</span> BookDao bookDao;</span><br><span class="line">   </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">print</span><span class="params">()</span></span>&#123;</span><br><span class="line">      System.out.println(bookDao);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;BookService [bookDao=&quot;</span> + bookDao + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//名字默认是类名首字母小写</span></span><br><span class="line"><span class="meta">@Repository</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BookDao</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> String lable = <span class="string">&quot;1&quot;</span>;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">getLable</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> lable;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setLable</span><span class="params">(String lable)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.lable = lable;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&quot;BookDao [lable=&quot;</span> + lable + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="MainConifgOfAutowired"><a href="#MainConifgOfAutowired" class="headerlink" title="MainConifgOfAutowired"></a>MainConifgOfAutowired</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 自动装配;</span></span><br><span class="line"><span class="comment"> *        Spring利用依赖注入（DI），完成对IOC容器中中各个组件的依赖关系赋值；</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 1）、<span class="doctag">@Autowired</span>：自动注入：</span></span><br><span class="line"><span class="comment"> *        1）、默认优先按照类型去容器中找对应的组件:applicationContext.getBean(BookDao.class);找到就赋值</span></span><br><span class="line"><span class="comment"> *        2）、如果找到多个相同类型的组件，再将属性的名称作为组件的id去容器中查找</span></span><br><span class="line"><span class="comment"> *                       applicationContext.getBean(&quot;bookDao&quot;)</span></span><br><span class="line"><span class="comment"> *        3）、<span class="doctag">@Qualifier</span>(&quot;bookDao&quot;)：使用<span class="doctag">@Qualifier</span>指定需要装配的组件的id，而不是使用属性名</span></span><br><span class="line"><span class="comment"> *        4）、自动装配默认一定要将属性赋值好，没有就会报错；</span></span><br><span class="line"><span class="comment"> *           可以使用<span class="doctag">@Autowired</span>(required=false);</span></span><br><span class="line"><span class="comment"> *        5）、<span class="doctag">@Primary</span>：让Spring进行自动装配的时候，默认使用首选的bean；</span></span><br><span class="line"><span class="comment"> *              也可以继续使用<span class="doctag">@Qualifier</span>指定需要装配的bean的名字</span></span><br><span class="line"><span class="comment"> *        BookService&#123;</span></span><br><span class="line"><span class="comment"> *           <span class="doctag">@Autowired</span></span></span><br><span class="line"><span class="comment"> *           BookDao  bookDao;</span></span><br><span class="line"><span class="comment"> *        &#125;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 2）、Spring还支持使用<span class="doctag">@Resource</span>(JSR250)和<span class="doctag">@Inject</span>(JSR330)[java规范的注解]</span></span><br><span class="line"><span class="comment"> *        <span class="doctag">@Resource</span>:</span></span><br><span class="line"><span class="comment"> *           可以和<span class="doctag">@Autowired</span>一样实现自动装配功能；默认是按照组件名称进行装配的；</span></span><br><span class="line"><span class="comment"> *           没有能支持<span class="doctag">@Primary</span>功能没有支持<span class="doctag">@Autowired</span>（reqiured=false）;</span></span><br><span class="line"><span class="comment"> *        <span class="doctag">@Inject</span>:</span></span><br><span class="line"><span class="comment"> *           需要导入javax.inject的包，和Autowired的功能一样。没有required=false的功能；</span></span><br><span class="line"><span class="comment"> *  <span class="doctag">@Autowired</span>:Spring定义的； <span class="doctag">@Resource</span>、<span class="doctag">@Inject</span>都是java规范</span></span><br><span class="line"><span class="comment"> *     </span></span><br><span class="line"><span class="comment"> * AutowiredAnnotationBeanPostProcessor:解析完成自动装配功能；       </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 3）、 <span class="doctag">@Autowired</span>:构造器，参数，方法，属性；都是从容器中获取参数组件的值</span></span><br><span class="line"><span class="comment"> *        1）、[标注在方法位置]：<span class="doctag">@Bean</span>+方法参数；参数从容器中获取;默认不写<span class="doctag">@Autowired</span>效果是一样的；都能自动装配</span></span><br><span class="line"><span class="comment"> *        2）、[标在构造器上]：如果组件只有一个有参构造器，这个有参构造器的<span class="doctag">@Autowired</span>可以省略，参数位置的组件还是可以自动从容器中获取</span></span><br><span class="line"><span class="comment"> *        3）、放在参数位置：</span></span><br><span class="line"><span class="comment"> 			public Boss(<span class="doctag">@Autowired</span> Car car)&#123;</span></span><br><span class="line"><span class="comment">				this.car = car;</span></span><br><span class="line"><span class="comment">				System.out.println(&quot;Boss...有参构造器&quot;);</span></span><br><span class="line"><span class="comment">			&#125;</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 4）、自定义组件想要使用Spring容器底层的一些组件（ApplicationContext，BeanFactory，xxx）；</span></span><br><span class="line"><span class="comment"> *        自定义组件实现xxxAware；在创建对象的时候，会调用接口规定的方法注入相关组件；Aware；</span></span><br><span class="line"><span class="comment"> *        把Spring底层一些组件注入到自定义的Bean中；</span></span><br><span class="line"><span class="comment"> *        xxxAware：功能使用xxxProcessor；</span></span><br><span class="line"><span class="comment"> *           ApplicationContextAware==》ApplicationContextAwareProcessor；</span></span><br><span class="line"><span class="comment"> *     </span></span><br><span class="line"><span class="comment"> *        </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> lfy</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@ComponentScan(&#123;&quot;com.atguigu.service&quot;,&quot;com.atguigu.dao&quot;,</span></span><br><span class="line"><span class="meta">   &quot;com.atguigu.controller&quot;,&quot;com.atguigu.bean&quot;&#125;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConifgOfAutowired</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Primary</span></span><br><span class="line">   <span class="meta">@Bean(&quot;bookDao2&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> BookDao <span class="title">bookDao</span><span class="params">()</span></span>&#123;</span><br><span class="line">      BookDao bookDao = <span class="keyword">new</span> BookDao();</span><br><span class="line">      bookDao.setLable(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">      <span class="keyword">return</span> bookDao;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@Bean</span>标注的方法创建对象的时候，方法参数的值默认从容器中获取</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@param</span> car</span></span><br><span class="line"><span class="comment">    * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">   <span class="meta">@Bean</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Color <span class="title">color</span><span class="params">(Car car)</span></span>&#123;</span><br><span class="line">      Color color = <span class="keyword">new</span> Color();</span><br><span class="line">      color.setCar(car);</span><br><span class="line">      <span class="keyword">return</span> color;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="IOCTest-Autowired"><a href="#IOCTest-Autowired" class="headerlink" title="IOCTest_Autowired"></a>IOCTest_Autowired</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IOCTest_Autowired</span> </span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Test</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test01</span><span class="params">()</span></span>&#123;</span><br><span class="line">      AnnotationConfigApplicationContext applicationContext = <span class="keyword">new</span> AnnotationConfigApplicationContext(MainConifgOfAutowired.class);</span><br><span class="line">      </span><br><span class="line">      BookService bookService = applicationContext.getBean(BookService.class);</span><br><span class="line">      System.out.println(bookService);</span><br><span class="line">      </span><br><span class="line">      <span class="comment">//BookDao bean = applicationContext.getBean(BookDao.class);</span></span><br><span class="line">      <span class="comment">//System.out.println(bean);</span></span><br><span class="line">      </span><br><span class="line">      Boss boss = applicationContext.getBean(Boss.class);</span><br><span class="line">      System.out.println(boss);</span><br><span class="line">      Car car = applicationContext.getBean(Car.class);</span><br><span class="line">      System.out.println(car);</span><br><span class="line">      </span><br><span class="line">      Color color = applicationContext.getBean(Color.class);</span><br><span class="line">      System.out.println(color);</span><br><span class="line">      System.out.println(applicationContext);</span><br><span class="line">      applicationContext.close();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="Profle"><a href="#Profle" class="headerlink" title="@Profle"></a>@Profle</h4><h5 id="MainConfigOfProfile"><a href="#MainConfigOfProfile" class="headerlink" title="MainConfigOfProfile"></a>MainConfigOfProfile</h5><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Profile：</span></span><br><span class="line"><span class="comment"> *        Spring为我们提供的可以根据当前环境，动态的激活和切换一系列组件的功能；</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 开发环境、测试环境、生产环境；</span></span><br><span class="line"><span class="comment"> * 数据源：(/A)(/B)(/C)；</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Profile</span>：指定组件在哪个环境的情况下才能被注册到容器中，不指定，任何环境下都能注册这个组件</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * 1）、加了环境标识的bean，只有这个环境被激活的时候才能注册到容器中。默认是default环境</span></span><br><span class="line"><span class="comment"> * 2）、写在配置类上，只有是指定的环境的时候，整个配置类里面的所有配置才能开始生效</span></span><br><span class="line"><span class="comment"> * 3）、没有标注环境标识的bean在，任何环境下都是加载的；</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@PropertySource(&quot;classpath:/dbconfig.properties&quot;)</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainConfigOfProfile</span> <span class="keyword">implements</span> <span class="title">EmbeddedValueResolverAware</span></span>&#123;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Value(&quot;$&#123;db.user&#125;&quot;)</span></span><br><span class="line">   <span class="keyword">private</span> String user;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> StringValueResolver valueResolver;</span><br><span class="line">   </span><br><span class="line">   <span class="keyword">private</span> String  driverClass;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Bean</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> Yellow <span class="title">yellow</span><span class="params">()</span></span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> Yellow();</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Profile(&quot;test&quot;)</span></span><br><span class="line">   <span class="meta">@Bean(&quot;testDataSource&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSourceTest</span><span class="params">(<span class="meta">@Value(&quot;$&#123;db.password&#125;&quot;)</span>String pwd)</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">      ComboPooledDataSource dataSource = <span class="keyword">new</span> ComboPooledDataSource();</span><br><span class="line">      dataSource.setUser(user);</span><br><span class="line">      dataSource.setPassword(pwd);</span><br><span class="line">      dataSource.setJdbcUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/test&quot;</span>);</span><br><span class="line">      dataSource.setDriverClass(driverClass);</span><br><span class="line">      <span class="keyword">return</span> dataSource;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Profile(&quot;dev&quot;)</span></span><br><span class="line">   <span class="meta">@Bean(&quot;devDataSource&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSourceDev</span><span class="params">(<span class="meta">@Value(&quot;$&#123;db.password&#125;&quot;)</span>String pwd)</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">      ComboPooledDataSource dataSource = <span class="keyword">new</span> ComboPooledDataSource();</span><br><span class="line">      dataSource.setUser(user);</span><br><span class="line">      dataSource.setPassword(pwd);</span><br><span class="line">      dataSource.setJdbcUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/ssm_crud&quot;</span>);</span><br><span class="line">      dataSource.setDriverClass(driverClass);</span><br><span class="line">      <span class="keyword">return</span> dataSource;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="meta">@Profile(&quot;prod&quot;)</span></span><br><span class="line">   <span class="meta">@Bean(&quot;prodDataSource&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSourceProd</span><span class="params">(<span class="meta">@Value(&quot;$&#123;db.password&#125;&quot;)</span>String pwd)</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">      ComboPooledDataSource dataSource = <span class="keyword">new</span> ComboPooledDataSource();</span><br><span class="line">      dataSource.setUser(user);</span><br><span class="line">      dataSource.setPassword(pwd);</span><br><span class="line">      dataSource.setJdbcUrl(<span class="string">&quot;jdbc:mysql://localhost:3306/scw_0515&quot;</span>);</span><br><span class="line">      </span><br><span class="line">      dataSource.setDriverClass(driverClass);</span><br><span class="line">      <span class="keyword">return</span> dataSource;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setEmbeddedValueResolver</span><span class="params">(StringValueResolver resolver)</span> </span>&#123;</span><br><span class="line">      <span class="comment">// TODO Auto-generated method stub</span></span><br><span class="line">      <span class="keyword">this</span>.valueResolver = resolver;</span><br><span class="line">      driverClass = valueResolver.resolveStringValue(<span class="string">&quot;$&#123;db.driverClass&#125;&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="dbconfig-properties"><a href="#dbconfig-properties" class="headerlink" title="dbconfig.properties"></a>dbconfig.properties</h5><figure class="highlight properties"><table><tr><td class="code"><pre><span class="line"><span class="meta">db.user</span>=<span class="string">root</span></span><br><span class="line"><span class="meta">db.password</span>=<span class="string">123456</span></span><br><span class="line"><span class="meta">db.driverClass</span>=<span class="string">com.mysql.jdbc.Driver</span></span><br></pre></td></tr></table></figure>











</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/1a003b7b.html">https://imlql.cn/post/1a003b7b.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring/">Spring</a><a class="post-meta__tags" href="/tags/%E6%B3%A8%E8%A7%A3/">注解</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/599156d.html"><img class="prev-cover" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/spring.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring源码系列-第1章-Spring源码纵览</div></div></a></div><div class="next-post pull-right"><a href="/post/e959db2e.html"><img class="next-cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/os_logo.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">操作系统-IO与零拷贝</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring%E6%B3%A8%E8%A7%A3"><span class="toc-text">Spring注解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#AnnotationConfigApplicationContext"><span class="toc-text">AnnotationConfigApplicationContext</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BB%84%E4%BB%B6%E6%B7%BB%E5%8A%A0"><span class="toc-text">组件添加</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Configuration-Bean"><span class="toc-text">@Configuration+@Bean</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#XML%E6%96%87%E4%BB%B6%E6%96%B9%E5%BC%8F"><span class="toc-text">XML文件方式</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#Person"><span class="toc-text">Person</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#beans-xml-%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6"><span class="toc-text">beans.xml-配置文件</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#MainTest"><span class="toc-text">MainTest</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%B3%A8%E8%A7%A3%E6%96%B9%E5%BC%8F"><span class="toc-text">注解方式</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ComponentScans"><span class="toc-text">@ComponentScans</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89TypeFilter%E6%8C%87%E5%AE%9A%E5%8C%85%E6%89%AB%E6%8F%8F%E8%A7%84%E5%88%99"><span class="toc-text">自定义TypeFilter指定包扫描规则</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Scope"><span class="toc-text">@Scope</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Lazy"><span class="toc-text">@Lazy</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Conditional"><span class="toc-text">@Conditional</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfig2"><span class="toc-text">MainConfig2</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#LinuxCondition"><span class="toc-text">LinuxCondition</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#WindowsCondition"><span class="toc-text">WindowsCondition</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Import"><span class="toc-text">@Import</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfig2-1"><span class="toc-text">MainConfig2</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#MyImportSelector"><span class="toc-text">MyImportSelector</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#MyImportBeanDefinitionRegistrar"><span class="toc-text">MyImportBeanDefinitionRegistrar</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#FactoryBean"><span class="toc-text">FactoryBean</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfig2-2"><span class="toc-text">MainConfig2</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#ColorFactoryBean"><span class="toc-text">ColorFactoryBean</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#IOCTest"><span class="toc-text">IOCTest</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-text">生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Bean%E6%8C%87%E5%AE%9A%E5%88%9D%E5%A7%8B%E5%8C%96%E5%92%8C%E9%94%80%E6%AF%81%E6%96%B9%E6%B3%95"><span class="toc-text">@Bean指定初始化和销毁方法</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#IOCTest-LifeCycle"><span class="toc-text">IOCTest_LifeCycle</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfigOfLifeCycle"><span class="toc-text">MainConfigOfLifeCycle</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BE%93%E5%87%BA"><span class="toc-text">输出</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#InitializingBean%E5%92%8CDisposableBean"><span class="toc-text">InitializingBean和DisposableBean</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfigOfLifeCycle-1"><span class="toc-text">MainConfigOfLifeCycle</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Cat"><span class="toc-text">Cat</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BE%93%E5%87%BA-1"><span class="toc-text">输出</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#PostConstruct%E5%92%8C-PreDestroy"><span class="toc-text">@PostConstruct和@PreDestroy</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfigOfLifeCycle-2"><span class="toc-text">MainConfigOfLifeCycle</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Dog"><span class="toc-text">Dog</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BE%93%E5%87%BA-2"><span class="toc-text">输出</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#BeanPostProcessor"><span class="toc-text">BeanPostProcessor</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MyBeanPostProcessor"><span class="toc-text">MyBeanPostProcessor</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B1%9E%E6%80%A7%E8%B5%8B%E5%80%BC"><span class="toc-text">属性赋值</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Value%E5%92%8C-PropertySource"><span class="toc-text">@Value和@PropertySource</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#Person-1"><span class="toc-text">Person</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#person-properties"><span class="toc-text">person.properties</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfigOfPropertyValues"><span class="toc-text">MainConfigOfPropertyValues</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#IOCTest-PropertyValue"><span class="toc-text">IOCTest_PropertyValue</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BE%93%E5%87%BA-3"><span class="toc-text">输出</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D"><span class="toc-text">自动装配</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Autowired-Qualifier-Primary-Resource-Inject"><span class="toc-text">@Autowired-@Qualifier-@Primary-@Resource-@Inject</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConifgOfAutowired"><span class="toc-text">MainConifgOfAutowired</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#IOCTest-Autowired"><span class="toc-text">IOCTest_Autowired</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Profle"><span class="toc-text">@Profle</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#MainConfigOfProfile"><span class="toc-text">MainConfigOfProfile</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#dbconfig-properties"><span class="toc-text">dbconfig.properties</span></a></li></ol></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>